<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\TemplatesLog;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Redis;
use App\Helper\Build\Build;
class Template extends Model
{
    //
    use SoftDeletes;
    
    protected $connection = 'mysql';
	
	public static $type = [ 1 => '首页模板', 2 => '封面模板', 3 => '内容模板', 4 => '专题模板', 5 => '公共模板' ];
	public static $default = [ 1 => '是', 0 => '否' ];
	//生成模板缓存后缀
	public static $temp_ext = '.blade.php';
	
	
	
	//更新模板保存记录
	public static function boot() {
        parent::boot();
        static::updated(function($model) {
			//
			if($model->original['content'] != $model->content)
			{
				$TemplatesLog = new TemplatesLog();
				$TemplatesLog->content = $model->content;
				$TemplatesLog->temp_id = $model->id;
				$TemplatesLog->save();
				//列表页/公共模板存入redis，前端公用redis 调取 生成模板
				if($model->type == 2 || $model->type == 5)self::set_redis_list_tmplate($model);
				
			}
            
        });
    }
	//列表页模板存入redis，前端公用redis 调取模板
	public static function set_redis_list_tmplate($row)
	{
		$content = $row->content;
		Redis::sadd(env('TEMP_SYNC_CACHE_KEY'), $row->id);
		Redis::set(env('TEMP_SYNC_CACHE_KEY').$row->id, replaceContent($content));
		
	}
	
	
	
	//模板选择
	public static function selectOptions($type)
	{
		$list = self::where('type', $type)->orderBy('is_default', 'desc')->select('id', 'title', 'is_default')->get();
		$arr = [];
		foreach($list as $row)
		{
			$arr[$row->id] = (($row->is_default==1)?'（默认）':'').$row->title;
		}
		return $arr;
	}
	//获取默认模板
	public function getDefault($type)
	{
		$row = self::where('type', $type)->where('is_default', 1)->select('id', 'title', 'content')->first();
		
		return $row;
	}
	//获取模板修改记录
	public function getTempLogs($id)
	{
		if(empty($id))return [];
		$list = TemplatesLog::where('temp_id', $id)->limit(10)->orderBy('id', 'desc')->get();
		
		return selectOptionsField($list, 'created_at');
	}
}
